var fs=require('fs');
var gd=require('gd');

exports.functions={
	admin_help_list_sections: function(space,lang) {
		var ret={};
		var path2="system/help/"+lang+"/";
		[space.system.paths.views,space.site.paths.views].forEach(function(path) {
			var dir=new fs.Directory(path+path2);
			if (!dir.exists()) return;
			dir.listFiles().forEach(function(f) {
				if (!f.match(/\.html$/)) return;
				var file=new fs.File(path+path2+f);
				file.open("r");
				var text=file.read().toString("utf-8");
				file.close();
				var h=f;
				var o=255;
				var arr;
				arr=text.match(/<!--\s*HEADER:\s*(\S.*?)\s*-->/);if (arr) h=arr[1];
				arr=text.match(/<!--\s*ORDER:\s*(\d+)\s*-->/); if (arr) o=arr[1];
				ret[f]={name: f.replace(/\.html$/,''), header: h,order:o};
			});
		});
		var tmp=[];
		for (i in ret) tmp.push(ret[i]);
		tmp.sort(function(a,b) {return a.order-b.order;});
		return tmp;
	}
};

exports.controllers={
	admin_help: function(space) {
		var lang;
		if (space.site) lang=space.site.language;
		if (!lang) lang=space.system.language;
		if (!space.fields.section) {
			space.help_sections=space.functions.admin_help_list_sections(space,lang);
			return space.views.process("widgets/admin_help/list",space);
		}
		space.help_section=space.views.process("system/help/"+lang+"/"+space.fields.section.replace(/[^\w\-]/g,''),space);
		return space.views.process("widgets/admin_help/view",space);
	}
};

